﻿using System;
using System.Collections.Generic;
using System.Windows;
using TheGameClient.Processes;

namespace TheGameClient
{
	public partial class SecSysUsernamePasswordControl : ISecuritySystem
	{
		private SecuritySystemState _state;

		public SecSysUsernamePasswordControl()
		{
			InitializeComponent();
		}

		public string Username
		{
			get { return txtUsername.Text; }
		}

		public string Password
		{
			get { return pwdPassword.Password; }
		}

		#region ISecuritySystem Members

		public event EventHandler<AccessAttemptEventArgs> BypassAttempt;
		public event EventHandler<AccessAttemptEventArgs> AccessAttempt;

		public Guid ProcessId { get; private set; }

		public ulong InterfaceId
		{
			get { return new Guid("{F869071A-51D0-4c0a-A851-F289BF2549A4}").ToLong(); }
		}

		public string ProcessName
		{
			get { return "Username/Password"; }
		}

		public InterfaceCategory Category
		{
			get { return InterfaceCategory.SecuritySystem; }
		}

		public SecuritySystemState State
		{
			get { return _state; }
			set
			{
				_state = value;
				switch (_state)
				{
				case SecuritySystemState.None:
					VisualStateManager.GoToState(this, "Default", true);
					break;
				case SecuritySystemState.Accessed:
				case SecuritySystemState.Bypassed:
					VisualStateManager.GoToState(this, "Accessed", true);
					break;
				case SecuritySystemState.AccountCreation:
					VisualStateManager.GoToState(this, "AccountCreation", false);
					break;
				}
			}
		}

		public void Bypass(IProgram bypasser)
		{
			if (BypassAttempt != null)
			{
				List<object> parameters = new List<object> {Username};
				BypassAttempt(this, new AccessAttemptEventArgs {Bypasser = bypasser, Parameters = parameters});
			}
		}

		public void Access()
		{
			//as per definition of the username/password secsys, the next 2 parameters required by it are: username, password.
			List<object> parameters = new List<object>
			{
				Username,
				Password.EncryptPassword()
			};

			if (AccessAttempt != null)
				AccessAttempt(this, new AccessAttemptEventArgs {Parameters = parameters});
		}

		public void SetBypassResult(bool successful)
		{
			if (!successful)
				return;
			VisualStateManager.GoToState(this, "Accessed", true);
		}

		public void SetAccessResult(bool successful)
		{
			if (!successful)
				return;
			VisualStateManager.GoToState(this, "Accessed", true);
		}

		#endregion

		private void BtnOkClick(object sender, RoutedEventArgs e)
		{
			Access();
		}
	}

	public class SecurityUsernamePasswordUiFactory : UiFactoryBase
	{
		public override InterfaceCategory UiCategory
		{
			get { return InterfaceCategory.SecuritySystem; }
		}

		public override IProcess CreateProgram()
		{
			return new SecSysUsernamePasswordControl();
		}
	}
}